package com.mindskip.xzs.security;

import com.mindskip.xzs.domain.enums.SystemCode;
import com.mindskip.xzs.domain.entity.UserEventLog;
import com.mindskip.xzs.event.UserEvent;
import com.mindskip.xzs.service.UserService;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.logout.SimpleUrlLogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;


/**
 * 用户成功登出后调用该方法
 */
@Component
public class RestLogoutSuccessHandler extends SimpleUrlLogoutSuccessHandler {

    private final UserService userService;

    // 让该类能获得事件发布的能力
    private final ApplicationEventPublisher applicationEventPublisher;

    public RestLogoutSuccessHandler(UserService userService, ApplicationEventPublisher applicationEventPublisher) {
        this.userService = userService;
        this.applicationEventPublisher = applicationEventPublisher;
    }

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        // 从 authentication 中获得SpringSecurity里的User
        User springSecurityUser = (User) authentication.getPrincipal();
        if (springSecurityUser != null) {
            com.mindskip.xzs.domain.entity.User user = userService.getUserByUserName(springSecurityUser.getUsername());
            UserEventLog userEventLog = new UserEventLog(user.getId(), user.getUserName(), user.getRealName(), new Date());
            userEventLog.setContent(user.getUserName() + " 登出了学之思开源考试系统");
            // 发布事件
            applicationEventPublisher.publishEvent(new UserEvent(userEventLog));
        }
        RestUtil.response(response, SystemCode.OK);
    }
}
